package com.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.tanhua.autoconfig.properties.OssProperties;
import com.tanhua.autoconfig.properties.SmsProperties;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class OssTemplate {
    //声明私有变量
    private OssProperties ossProperties;
    //初始化构造方法（让其可以使用）
    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }
    @SneakyThrows
    public String uploadFile(String filename, InputStream inputStream) {
        // 阿里云OSS相关配置
        String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // 替换为您的Endpoint
        String accessKeyId = ossProperties.getAccessKey(); // 替换为您的AccessKeyId
        String accessKeySecret = ossProperties.getSecret(); // 替换为您的AccessKeySecret
        String bucketName = ossProperties.getBucketName(); // 替换为您的Bucket名称
        //3.拼写图片路径
        String fileName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())+
                "/"+ UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));
        // 创建OSSClient实例
        OSS ossClient = null;

        // 使用默认的CredentialProvider链
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 定义要上传的byte数组内容

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);

        // 执行上传操作
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        String url =  ossProperties.getUrl()+fileName;
        return url;


    }
}
